const Koa = require('koa')
const app = new Koa()
const fs = require('fs')
const fetch = require('node-fetch')
const onerror = require('koa-onerror')
const Router = require('koa-router')
const bodyParse = require('koa-bodyparser')
const querystring = require('querystring')
const FormData = require('form-data');

onerror(app)

const router = new Router()
app.use(bodyParse())
router.get('/redirect', (ctx, next) => {
  let url = "http://passport.siwi.dev/oauth/authorize?client_id=3&redirect_uri=http://blog.siwi.dev/callback&response_type=code&scope="
  ctx.redirect(url);
})
router.get('/', async (ctx, next) => {
  console.log(ctx)
  ctx.body = ctx
})
router.get('/callback', async (ctx, next) => {
  
  const form = new FormData()
  form.append('grant_type', 'authorization_code')
  form.append('client_id', 'client-id')
  form.append('client_secret', 'KzGZrA2bJoUp5nG5zjIhoUBO45QrBfb9YFkf9AcF')
  form.append('redirect_uri', 'http://blog.siwi.me/callback')
  form.append('code', ctx.query.code)
  fetch('http://passport.siwi.dev/oauth/token', {
    method: 'POST',
    body: form
  }).then(function (res) {
    return res.json()
  }).then(function (json) {
    console.log(json)
  })

  ctx.body = querystring.stringify(form)
})
router.get('/test', async (ctx, next) => {
  ctx.body = test
})

app.use(router.routes())
app.listen(3000, (err) => {
  if (err) throw err
  console.log('运行在在3000端口')
})